package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.LearnRecordBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wo on 2015/11/10.
 */
public class VowelStudyView extends LinearLayout {
    private Context mContext = null;
    private Cursor cursor;
    private List<AppDataBean> mDataList;
    private int currentPosition = 0;
    private int lessonType = 4;

    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;

    private View mView = null;
    private PlayControlView mPlayController;
    private ImageView mPronunciationView1, mPronunciationView2, mPronunciationView3;
    private TextView mWordView;

    public VowelStudyView(Context context) {
        super(context);
        mContext = context;
        Typeface type = Typeface.createFromAsset(getContext().getAssets(), "fonts/hanyupinyin.ttf");
        mView = LayoutInflater.from(context).inflate(R.layout.pronunciation_viewer_layout, null);
        mPlayController = (PlayControlView)mView.findViewById(R.id.pronu_play_controller);
        mPronunciationView1 = (ImageView)mView.findViewById(R.id.pronu_img_1);
        mPronunciationView2 = (ImageView)mView.findViewById(R.id.pronu_img_2);
        mPronunciationView3 = (ImageView)mView.findViewById(R.id.pronu_img_3);
        mWordView = (TextView)mView.findViewById(R.id.pronu_text);
        mWordView.setTypeface(type);
        this.addView(mView);
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while(cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            mDataList.add(d);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        Logger.e("xionghy - " + mDataList.size());
        Logger.e("xionghy: " + mDataList.get(currentPosition).toString());
        updateViewData();
    }

    private void updateViewData() {
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        AppDataBean data = mDataList.get(currentPosition);
        mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        mWordView.setText(data.getPinyin().replace("|", ""));
        mPlayController.setStandardUrl(mMp3SourceDir);
        mPlayController.setPlayRecordVisibility(View.INVISIBLE);
        mPlayController.playStandard();
        String picFileNames[] = data.getPicName().replace("|", " ").split(" ");
        if (picFileNames.length == 1) {
            mPronunciationView1.setVisibility(View.VISIBLE);
            mPronunciationView2.setVisibility(View.GONE);
            mPronunciationView3.setVisibility(View.GONE);
            Bitmap bmp1 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[0] + ".png");
            mPronunciationView1.setImageBitmap(bmp1);
        } else if (picFileNames.length == 2) {
            mPronunciationView1.setVisibility(View.VISIBLE);
            mPronunciationView2.setVisibility(View.VISIBLE);
            mPronunciationView3.setVisibility(View.GONE);
            Bitmap bmp1 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[0]+ ".png");
            mPronunciationView1.setImageBitmap(bmp1);
            Bitmap bmp2 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[1]+ ".png");
            mPronunciationView2.setImageBitmap(bmp2);
        } else {
            mPronunciationView1.setVisibility(View.VISIBLE);
            mPronunciationView2.setVisibility(View.VISIBLE);
            mPronunciationView3.setVisibility(View.VISIBLE);
            Bitmap bmp1 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[0]+ ".png");
            mPronunciationView1.setImageBitmap(bmp1);
            Bitmap bmp2 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[1]+ ".png");
            mPronunciationView2.setImageBitmap(bmp2);
            Bitmap bmp3 = getBitmapFromAssets(AppResourceMap.getMp3Fold(lessonType) + picFileNames[2]+ ".png");
            mPronunciationView2.setImageBitmap(bmp3);
        }
        addLearnRecord(data);
    }

    public void setListener(LessonProgressInterface listener) {  mListener = listener; }

    public void setNextListener(NextLessonInterface listener) { mNextListener = listener; }

    public void setCurrentPosition(int pos) { currentPosition = pos; }

    public void setVolumeListener(VolumeListener l) { mPlayController.setVolumeListener(l); }

    public void setRecordListener(RecordStatusListener l) { mPlayController.setRecordListener(l); }

    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        mPlayController.resetProgressBar();
        currentPosition ++;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
            Utils.showDialog((Activity)mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
        }
    }

    public void beforeWord() {
        if (currentPosition <= 0)
            return;
        mPlayController.resetProgressBar();
        currentPosition --;
        if (currentPosition < mDataList.size()) {
            updateViewData();
        } else {
            // TODO 进入下一课. 会掉到StudyActivity页面来进行View的切换
//            mNextListener.onLessonChanged(lessonType - 1);
        }
    }

    private void addLearnRecord(AppDataBean data) {
        LearnRecordBean bean = new LearnRecordBean();
        bean.setChinese(data.getChinese());
        bean.setLearnedTimes(1);
        bean.setLearnType(lessonType + "");
        bean.setRecordID(data.getType() + "|" + data.getWeight());
        bean.setTimestamp(System.currentTimeMillis() + "");
        DBHelper.getInstance(mContext).insertLearnRecord(bean);
    }

    public void onDestroy() {
        if (mPlayController != null) {
            mPlayController.destory();
        }
        if (cursor != null)
            cursor.close();
        SimpleRecordUtil.getInstance(mContext).stopPlayer();
        SimpleRecordUtil.getInstance(mContext).stopRecorder();
    }

    private Bitmap getBitmapFromAssets(String name) {
        Bitmap bmp = null;
        AssetManager am = mContext.getAssets();
        try {
            InputStream stream = am.open(name);
            bmp = BitmapFactory.decodeStream(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmp;
    }
}
